// import { parseToObject } from '@/utils';
import MtGrabTaskService from './api';
// import { listMtGrapTaskByPage } from './api';
import { AddWeiziTask, AddShushuoTask } from './components';
import Utils from './CommonUtils';
import { MessageBox, Message, Loading } from 'element-ui';
// import { export_json_to_excel } from "../utils/Export2Excel";

export default {
  data() {
    return {
      taskId: '',
      taskName: null,
      tableData: [],
      tableLoading: false,
      subTaskVisible: false,
      subTaskTableData: [],
      total: 0,
      curentPage: 1,
      pageSize: 10,
      pageNum: 1,
      detailInfo: '',
      detailInfoCloseable: false,
      addTaskWindowVisible: false,
      addWweiziTaskVisible: false,
      addShushuoTaskVisible: false,
      mtStoreTable: [],
      addTaskTitle: '新增任务',
      readOnly: true,
      taskForm: {
        taskName: '',
        locationType: 'self',
        address: '',
        yfChannelCode: '',
        storeKeyword: '',
        retryNum: '1',
      },
      exportPlatformCode: 'MTWM',
      taskType: 'WEIZI',
      exportSzDialogVisible: false,
      pickerOptions: {
        disabledDate(time) {
          const start = new Date();
          let startTime = start.getTime() - 3600 * 1000 * 24 * 31;
          return time.getTime() < startTime;
        },
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
      dateRange: [],
    };
  },
  async created() {
    // 加载数据
    this.loadMtGrapTaskData();
    // 初始化时间
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    this.dateRange[0] = Utils.formatDate(start);
    this.dateRange[1] = Utils.formatDate(end);
  },
  components: {
    AddWeiziTask: AddWeiziTask,
    AddShushuoTask: AddShushuoTask,
  },
  methods: {
    async loadMtGrapTaskData() {
      let crawlerTaskForm = {
        taskId: this.taskId,
        taskName: this.taskName,
      };
      let page = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      let params = {
        crawlerTaskForm: crawlerTaskForm,
        page: page,
      };
      //this.tableLoading = true;
      let list = await MtGrabTaskService.listMtGrapTaskByPage(params);
      console.log(list);
      //this.tableLoading = false;
      this.tableData = list.rows;
      this.total = Number.parseInt(list.total);
      if (list.total == 0) {
        this.pageNum = 1;
        this.pageSize = 10;
        Message({
          showClose: true,
          message: '没有查询到数据',
          type: 'warning',
        });
        return;
      }
    },
    search() {
      this.loadMtGrapTaskData();
    },
    handleSizeChange(pageSize) {
      console.log(`每页 ${pageSize}`);
      this.pageSize = pageSize;
      this.loadMtGrapTaskData();
    },
    handleCurrentChange(pageNum) {
      console.log(`当前页: ${pageNum}`);
      this.pageNum = pageNum;
      this.loadMtGrapTaskData();
    },
    async nearMtStore(row) {
      console.log(row);
    },
    async addTask(readOnly, row) {
      this.readOnly = readOnly;
      this.addTaskWindowVisible = true;
      if (!readOnly) {
        this.addTaskTitle = '新增任务';
        this.taskForm = {
          taskName: '',
          locationType: 'self',
          address: '',
          yfChannelCode: '',
          storeId: [],
          retryNum: '1',
          storeName: [],
        };
      } else {
        this.addTaskTitle = '查看任务';
        let result = await MtGrabTaskService.getTaskDetail(row.id);
        this.taskForm = result;
      }
    },
    addWeiziTask() {
      this.addWweiziTaskVisible = true;
      this.taskForm.taskName = null;
    },
    addShushuoTask() {
      this.addShushuoTaskVisible = true;
      this.taskForm.taskName = null;
    },
    closeWeiziTaskWindow() {
      this.addWweiziTaskVisible = false;
      this.loadMtGrapTaskData();
    },
    closeShushuoTaskWindow() {
      this.addShushuoTaskVisible = false;
      this.loadMtGrapTaskData();
    },
    editTask(row) {
      console.log('edit ==>', row);
    },
    taskTypeFormatter(row) {
      if (row.taskType == 'WEIZI') {
        return '微子';
      } else {
        return '数说';
      }
    },
    dateFormatter(row) {
      return this.formatDateTime(row.createTime);
    },
    formatDateTime(inputTime) {
      var date = new Date(inputTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? '0' + m : m;
      var d = date.getDate();
      d = d < 10 ? '0' + d : d;
      var h = date.getHours();
      h = h < 10 ? '0' + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? '0' + minute : minute;
      second = second < 10 ? '0' + second : second;
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
    },
    async cancelTask(row) {
      let loading = Loading.service({
        lock: true,
        text: '取消中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      await MtGrabTaskService.cancelTask({ taskId: row.id });
      loading.close();
      this.loadMtGrapTaskData();
    },
    confirmCancelTask(row) {
      MessageBox.confirm('此操作会取消任务（取消能取消成功的，可能不包括所有），确定?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.cancelTask(row);
        })
        .catch(() => {});
    },
    async deleteTask(row) {
      MessageBox.confirm('是否删除编码为【' + row.id + '】的任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.doDeleteTask(row);
          Message({
            type: 'success',
            message: '删除成功!',
          });
        })
        .catch(() => {});
    },
    async doDeleteTask(row) {
      await MtGrabTaskService.deleteById(row.id);
      this.loadMtGrapTaskData();
    },
    closaddTaskWindow(reload) {
      console.log('父类方法, reload=> ', reload);
      if (reload) {
        this.loadMtGrapTaskData();
      }
      this.addTaskWindowVisible = false;
    },
    async listSubTask(row) {
      let result = await MtGrabTaskService.listSubTask({ taskId: row.id });
      this.subTaskTableData = result;
      this.subTaskVisible = true;
      let running = 0,
        finish = 0,
        retry = 0,
        failed = 0,
        count = 0,
        cancel = 0;
      console.log(this.subTaskTableData);
      this.subTaskTableData.forEach(std => {
        count = ++count;
        if (std.status == 'RUNNING') {
          running = ++running;
        } else if (std.status == 'FAILED') {
          failed = ++failed;
        } else if (std.status == 'RETRY') {
          retry = ++retry;
        } else if (std.status == 'FINISH') {
          finish = ++finish;
        } else if (std.status == 'CANCEL') {
          cancel = ++cancel;
        }
      });
      this.detailInfo =
        '共' +
        count +
        '个任务，运行中的' +
        running +
        '个；完成' +
        finish +
        '个；重试中的' +
        retry +
        '个；失败的' +
        failed +
        '个；取消的' +
        cancel +
        '个';
    },
    async downloadSku(row) {
      let result = await MtGrabTaskService.getTaskDetail({ taskId: row.id });
      if (result.exportUrl) {
        window.open(result.exportUrl);
      } else {
        Message({
          showClose: true,
          message: '暂无导出任务或数据正在导出中.....',
          type: 'warning',
        });
      }
    },
    async exportData(row) {
      let taskDetail = await MtGrabTaskService.getTaskDetail({ taskId: row.id });
      if (taskDetail.isExport == 'Y') {
        MessageBox.confirm('此任务已经生成过下载文件，是否重复生成?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.doExportData(row);
        });
      } else {
        this.doExportData(row);
      }
    },
    async doExportData(row) {
      let loading = Loading.service({
        lock: true,
        text: '导出中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      let result;
      result = await MtGrabTaskService.exportWeiziSku({ taskId: row.id });
      loading.close();
      this.loadMtGrapTaskData();
      if (result == 'ok') {
        Message({
          showClose: true,
          message: '此为异步下载数据，已收到请求，请5分钟后来下载数据',
          type: 'success',
          duration: 15000,
        });
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    showSzWindow() {
      this.exportSzDialogVisible = true;
    },
    async exportWeiziSz() {
      const exportWzSzLoading = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      console.log(this.dateRange);
      let result = await MtGrabTaskService.exportStore({
        taskType: this.taskType,
        platformCode: this.exportPlatformCode,
        startTime: this.patchZero(this.dateRange[0]),
        endTime: this.patchZero(this.dateRange[1]),
      });
      window.open(result);
      this.exportSzDialogVisible = false;
      exportWzSzLoading.close();
    },
    patchZero(dateStr) {
      let dateArray = dateStr.split('-');
      let year = dateArray[0];
      let month = dateArray[1].length < 2 ? '0' + dateArray[1] : dateArray[1];
      let day = dateArray[2].length < 2 ? '0' + dateArray[2] : dateArray[2];
      return year + '-' + month + '-' + day;
    },
  },
};
